package domain.gbshaasrode.spreadsheet;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

import domain.DomainException;

public class GBSOpvangSpreadSheet {
	
	private GBSHaasrodeSpreadSheetService gbsHaasrodeService;
	private SpreadsheetEntry gbsHaasrodeSS;
		
	public GBSOpvangSpreadSheet(GBSHaasrodeSpreadSheetService service) throws DomainException{
		
		setGbsHaasrodeService(service);
		try {
			URL SPREADSHEET_FEED_URL = new URL(
					"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
			SpreadsheetFeed feed = getGbsHaasrodeService().getService().getFeed(SPREADSHEET_FEED_URL,
					SpreadsheetFeed.class);
			List<SpreadsheetEntry> spreadsheets = feed.getEntries();			
			for(SpreadsheetEntry spreadsheet: spreadsheets){
				if(spreadsheet.getTitle().getPlainText().equals("GBSHaasrodeOpvang")){
					setGbsHaasrodeSS(spreadsheet);		
				}
			}
		} catch (AuthenticationException e) {
			throw new DomainException("Cannot authenticate",e);
		} catch (MalformedURLException e) {
			throw new DomainException("Wrong url",e);
		} catch (IOException e) {
			throw new DomainException("Cannot read",e);
		} catch (ServiceException e) {
			throw new DomainException("Google docs service unavailable",e);
		}		
	}

	public GBSHaasrodeSpreadSheetService getGbsHaasrodeService() {
		return gbsHaasrodeService;
	}

	private void setGbsHaasrodeService(GBSHaasrodeSpreadSheetService gbsHaasrodeService) {
		this.gbsHaasrodeService = gbsHaasrodeService;
	}

	public SpreadsheetEntry getGbsHaasrodeSS() {
		return gbsHaasrodeSS;
	}

	public void setGbsHaasrodeSS(SpreadsheetEntry gbsHaasrodeSS) {
		this.gbsHaasrodeSS = gbsHaasrodeSS;
	}
	
	@Override
	public String toString(){
		String overview = "";
	    List<WorksheetEntry> worksheets;
		try {
			worksheets = getGbsHaasrodeSS().getWorksheets();
			// Iterate through each worksheet in the spreadsheet.
		    for (WorksheetEntry worksheet : worksheets) {
		      // Get the worksheet's title, row count, and column count.
		      String title = worksheet.getTitle().getPlainText();
		      int rowCount = worksheet.getRowCount();
		      int colCount = worksheet.getColCount();

		      // Print the fetched information to the screen for this worksheet.
		      overview += "\t" + title + "- rows:" + rowCount + " cols: " + colCount + "\n";
		    }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	    
		return overview;
	}

}
